/**
 * Copyright (c) 2010
 * Bert Young. UESTC. 
 */
 
#ifndef BERT_TASKMANAGER_H
#define BERT_TASKMANAGER_H

#include "Mutex.h"
#include "EntryManager.h"

template <typename TASK>// class TASK : public Entry
class TaskManager : public EntryManager
{
protected:
	/**
	 * Lock for container
	 */
	RWLock lock;
public:
	/**
	 * Destructor
	 */
	virtual ~TaskManager()
	{
	}
	/**
	 * 	Callback on every TASK
	 */
	template < typename T>
		bool execEveryTask(Callback<T> & exec)
		{
			lock.rdlock();
			bool ret = execEveryEntry<T>(exec);
			lock.unlock();
			return ret;
		}
	/**
	 * Add task
	 */
	bool addTask(TASK * task)
	{
		lock.wrlock();
		bool ret = addEntry(task);
		lock.unlock();
		return ret;
	}
	/**
	 * Remove task
	 */
	bool removeTask( TASK * task )
	{
		lock.wrlock();
		bool ret = removeEntry(task);
		lock.unlock();
		return ret;
	}
	/**
	 * 得到连接数量
	 */
	unsigned int getSize() const
	{
		return size();
	}
	/**
	 * Get task
	 */
	TASK * getTaskByID( unsigned int id)
	{
		lock.rdlock();
		TASK * ret = (TASK *)getEntry(id);
		lock.unlock();
		return ret;
	}
	/**
	 * Broadcast msg to all tasks
	 */
	bool broadcast( const void * cmd, unsigned int len)
	{
		struct Broadcast : public Callback<TASK>
		{
			const void * cmd;
			unsigned int len;
			Broadcast(const void * c, unsigned int l) : cmd(c), len(l)
			{
			}
			bool exec( TASK * t)
			{
				if ( !t->shouldDisconnect() )//理论上不用这个判断；
				//因为本方法由逻辑线程操作，而TASK进入到这个容器，那一定是ok状态
				//如果shouldDisconnect为真的话，应该移出了这个容器
					t->sendPacket(cmd, len);
				return true;
			}
		}sendToAll(cmd, len);
		execEveryTask(sendToAll);
		return true;
	}
	/**
	 * 逻辑线程解析每一条连接收到的消息
	 */
	void doCmd()
	{
		struct DoCmd : public Callback<TASK>
		{
			bool exec( TASK * t)
			{
				if ( !t->shouldDisconnect() )
				{
					t->doCmd();
				}
				return true;
			}
		}parseCmd;
		execEveryTask(parseCmd);
	}

};

#endif
